import { createI18n,useI18n } from 'vue-i18n';
import zh from 'src/plugins/language/zh';
import en from 'src/plugins/language/en';
import { useStore } from 'src/plugins/pinia';
import { getCache,keys,storeToRefs } from 'src/plugins/pinia/common';
import { computed } from 'vue';

const messages = {
    en,
    zh,
};
const defaultLanguage = (navigator?.language || 'zh').toLocaleLowerCase().split('-')[0];
export const setLang = (lang=defaultLanguage) => {
    const { sys } = useStore();
    sys.$patch({lang});
};
export const getLang = () => getCache(keys.sys)?.lang || defaultLanguage;

const language = getLang(); // 这是获取浏览器的语言

const i18n = createI18n({
    locale: language,
    legacy: false,
    globalInjection: true,
    fallbackLocale: defaultLanguage, // 设置备用语言
    messages,
});

const keyMap = new Map();
export const getLangValue = key => {
    const { t } = useI18n();
    if (keyMap.get(key)) {
        return keyMap.get(key).value;
    }
    const c = computed(() => t(key));
    keyMap.set(key, c);
    return c.value;
};

export function getName(m) {
    const { sys } = useStore();
    const {lang} = storeToRefs(sys);
    if (lang.value === 'en') {
        return m.enName;
    }
    if (lang.value === 'zh') {
        return m.name;
    }
}

export const registerLang = app => {
    app.use(i18n);
};

